<?php
/*-----------------------------------------------------------------
* 	$Id: xajax.cseofunctions.php 573 2013-08-22 06:31:36Z akausch $
* 	Copyright (c) 2011-2021 commerce:SEO by Webdesign Erfurt
* 	http://www.commerce-seo.de
* ------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
* 	Released under the GNU General Public License
* ---------------------------------------------------------------*/

require_once (DIR_FS_INC.'xtc_parse_search_string.inc.php');
require (DIR_WS_INCLUDES.'xajax/xajax_core/xajax.inc.php');

$xajax = new xajax();
$xajax->setCharEncoding('UTF-8');
$xajax->setRequestURI($_SERVER['PHP_SELF']);

$xajax->registerFunction("kerimsuche");
$xajax->registerFunction("getFilterItems");
$xajax->registerFunction("getNewPrice");

function zeichen_ersetzen($string) {
	$string = str_replace('%E4', "&auml;", $string);
	$string = str_replace('%FC', "&uuml;", $string);
	$string = str_replace('%F6', "&ouml;", $string);
	$string = str_replace('%DF', "&szlig;", $string);
	$string = str_replace('\t', "", $string);
	$string = str_replace('\n', "", $string);
	$string = trim($string);
	return $string;
}
function kerimsuche($suchtext) {
	$suchtext = trim(urldecode(zeichen_ersetzen($suchtext)));
	if (strlen($suchtext) > 0) {
		if (!xtc_parse_search_string(stripslashes($suchtext), $search_keywords)) {
			$errorno += 10000000;
			$error = 1;
			$keyerror = 1;
		}
	}
	// define additional filters //
	//fsk18 lock
	if ($_SESSION['customers_status']['customers_fsk18_display'] == '0') {
		$fsk_lock = " AND p.products_fsk18 != '1' ";
	} else {
		unset ($fsk_lock);
	}
	//group check
	if (GROUP_CHECK == 'true') {
		$group_check = " AND p.group_permission_".$_SESSION['customers_status']['customers_status_id']."=1 ";
	} else {
		unset ($group_check);
	}
	//build query
	$select_str = "SELECT distinct
					p.products_id,
					p.products_model,
					p.products_fsk18,
					p.products_image,
					p.products_slave_in_list,
					p.products_master,
					pd.products_name,
					pd.products_description ";
	
	$from_str  = "FROM ".TABLE_PRODUCTS." AS p LEFT JOIN ".TABLE_PRODUCTS_DESCRIPTION." AS pd ON (p.products_id = pd.products_id) ";
	if (SEARCH_IN_ATTR == 'true') { 
		$from_str .= " LEFT OUTER JOIN ".TABLE_PRODUCTS_ATTRIBUTES." AS pa ON (p.products_id = pa.products_id) LEFT OUTER JOIN ".TABLE_PRODUCTS_OPTIONS_VALUES." AS pov ON (pa.options_values_id = pov.products_options_values_id) "; 
	}

	//where-string
	$where_str = " WHERE 
						p.products_status = '1' 
					AND 
						(p.products_slave_in_list = '1' OR p.products_master = '1' OR ((p.products_slave_in_list = '0' OR p.products_slave_in_list = '') AND (p.products_master_article = '' OR p.products_master_article = '0')))						
					AND 
						pd.language_id = '".(int) $_SESSION['languages_id']."'".
					$fsk_lock.$group_check;

	//go for keywords... this is the main search process
	if (isset ($suchtext) && xtc_not_null($suchtext)) {
		if (xtc_parse_search_string(stripslashes($suchtext), $search_keywords)) {
			$where_str .= " AND ( ";
			for ($i = 0, $n = sizeof($search_keywords); $i < $n; $i ++) {
				switch ($search_keywords[$i]) {
					case '(' :
					case ')' :
					case 'and' :
					case 'or' :
						$where_str .= " ".$search_keywords[$i]." ";
						break;
					default :
						$where_str .= " ( ";
						$where_str .= "pd.products_keywords LIKE ('%".html_entity_decode(addslashes($search_keywords[$i]))."%') ";
						$where_str .= "OR pd.products_name LIKE ('%".html_entity_decode(addslashes($search_keywords[$i]))."%') ";
						$where_str .= "OR p.products_model LIKE ('%".html_entity_decode(addslashes($search_keywords[$i]))."%') ";
						if (SEARCH_IN_DESC == 'true') {
						   $where_str .= "OR pd.products_description LIKE ('%".html_entity_decode(addslashes($search_keywords[$i]))."%') ";
						}						
						
						if (SEARCH_IN_ATTR == 'true') {
						   $where_str .= "OR (pov.products_options_values_name LIKE ('%".html_entity_decode(addslashes($search_keywords[$i]))."%') ";
						   $where_str .= "AND pov.language_id = '".(int) $_SESSION['languages_id']."')";
						}
						$where_str .= " ) ";
						break;
				}
			}
			$where_str .= " ) ORDER BY pd.products_name";
		}
	}
	//glue together
	$sql = $select_str.$from_str.$where_str;
	require_once(DIR_WS_CLASSES.'class.xtcprice.php');
	$xtPrice = new xtcPrice($_SESSION['currency'], $_SESSION['customers_status']['customers_status_id']);
	$result = "";
	$objResponse = new xajaxResponse();
	if (strlen($suchtext)>3) {
		$result .= "<div class='suggest_intro'>" . AUTOSUGGEST_INTRO . "</div>";
		$product_query = xtc_db_query($sql);
		$counter = 0;
		$more_result = 'false';
		while($product_array = xtc_db_fetch_array($product_query)) {
			$counter++;
			if ($counter <= 10) {
				$image = '';
				if ($product_array['products_image'] == '')
					$product_array['products_image'] = 'no_img.jpg';
				if ($product_array['products_image'] != '' && file_exists(DIR_WS_MINI_IMAGES.$product_array['products_image'])) {
					$image = DIR_WS_MINI_IMAGES.$product_array['products_image'];
					$image = '<div id="suggest_image"><a href="'.xtc_href_link(FILENAME_PRODUCT_INFO, xtc_product_link($product_array['products_id'], $product_array['products_name'])).'">'.xtc_image($image, $product_array['products_name']).'</a></div>';
				}
				$result .= '<div class="suggest_link">';
	            $result .= '<div>
								<div class="suggest_image">
									' . $image . '
								</div>
								<div class="suggest_productsname" id="suggestlink">
									<a href="'.xtc_href_link(FILENAME_PRODUCT_INFO, xtc_product_link($product_array['products_id'], $product_array['products_name'])).'">' . $product_array['products_name'] . '</a>
								</div>
							</div>';
	            $result .= '</div>';
			} else {
				$more_result = 'true';
			}
        }
		if ($counter == 0) {
			$result = '<div class="suggest_no_products">' . AUTOSUGGEST_NO_PRODUCTS . '</div>';
			$objResponse->addAssign("search_suggest", "style.height", '65px');
		} else {			
			if ($counter < 12) {
				$objResponse->addAssign("search_suggest", "style.height", (($counter*36)+195).'px');
			} else {
				$objResponse->addAssign("search_suggest", "style.height", '590px');
			}
		}
		$result .= '<div class="suggest_close"><a onclick="suggestClose(this);return false" class="suggestclose_link">'.AUTOSUGGEST_CLOSE.'</a></div>';
		if($more_result == 'true') {
			$result .= '<div class="suggest_more"><a';
			$result .= " onclick='javascript:more_result(\"".$suchtext."\");'  id='suggestmore_link'>";
			$result .= ''.MORE_RESULTS.'</a></div>';
		}
		$objResponse->addAssign("search_suggest", "style.display", 'block');
        $objResponse->addAssign("search_suggest", "innerHTML", $result);
	} else {
        $objResponse->addAssign("search_suggest", "style.display", 'none');
    }
	return $objResponse;
}

#########################################################
# Filter XAJAX
#########################################################

function getFilterItems($aFormValues) {
	$objResponse = new xajaxResponse();
	$fItems = array();
	$in = "";
	
	if(is_array($aFormValues)) {
		$post_array = $aFormValues;
		$filter_items = $post_array['filter'];
	} else {
		$zeichenkette = $aFormValues;
		$suchmuster = '/\[(.*?)\]/i';
		preg_match($suchmuster, $zeichenkette, $treffer);
		$new_clean = str_replace('"', '', $treffer[1]);
		$new_explode = explode('&', $new_clean);
		$filter_items = $new_explode;
		$zeichenkette = str_replace('"', '', $zeichenkette);
		$zeichenkette = str_replace('{', '', $zeichenkette);
		$zeichenkette = str_replace('}', '', $zeichenkette);

		$exploded = explode('&', $zeichenkette);
		
		for($i=0; sizeof($exploded) > $i; $i++) {
			$trennen = explode('=', $exploded[$i]);
			if($trennen[0] != '' && $trennen[1] !='' && !strstr($trennen[1], '[') && !strstr($trennen[1], ']'))
				$post_array[$trennen[0]] = $trennen[1];
		}

		$tmp = array();
		$k = 0;
		for($i = 0; sizeof($exploded) > $i; $i++) {
			if(strpos($exploded[$i], 'filter') !== false)
			{
				$tmp[$i] = explode('=', $exploded[$i]);
				$fItems[$k] = $tmp[$i][1];
				$k++;
			}
			else
				continue;					
		}
	}
	
	for($i = 0; $i < sizeof($fItems); $i++) {
		if($i == 0)
			$in .= (int)$fItems[$i];
		else
			$in .= ",".(int)$fItems[$i];
	}

	$having = '';
	if($post_array['verbinder'] == 'true' && $in !='') {
		$having = "HAVING CHAR_LENGTH(filter) > ".(strlen(str_replace('\'', '', $in)) - 1);
	}

	if($in !='') {
		$data_query = xtDBquery("SELECT
										GROUP_CONCAT(p2f.filter_id) AS filter,
										p2f.products_id
									FROM
										products_to_filter p2f,
										product_filter_items fi
									WHERE
										p2f.filter_id IN(".$in.")
									AND
										fi.id = p2f.filter_id
									GROUP BY
										p2f.products_id ".$having);

		while($data = xtc_db_fetch_array($data_query)){
			if($products_ids != '') {
				$products_ids .= ",'".$data['products_id']."'";
			} else {
				$products_ids = "'".$data['products_id']."'";
			}
		}

		if($products_ids =='') {
			$products_ids = "''";
		}

		if ($_SESSION['customers_status']['customers_fsk18_display'] == '0') {
			$fsk_lock = " AND p.products_fsk18 != '1' ";
		} else {
			unset($fsk_lock);
		}

		if (GROUP_CHECK == 'true') {
			$group_check = " AND p.group_permission_".$_SESSION['customers_status']['customers_status_id']."=1 ";
		} else {
			unset($group_check);
		}

		$select_str = "SELECT
						  p.products_id,
						  p.products_price,
						  p.products_model,
						  p.products_quantity,
						  p.products_shippingtime,
						  p.products_fsk18,
						  p.products_image,
						  p.products_weight,
						  p.products_tax_class_id,
						  pd.products_name,
						  pd.products_short_description ";

		$from_str = "FROM ".TABLE_PRODUCTS." AS p LEFT JOIN ".TABLE_PRODUCTS_DESCRIPTION." AS pd ON (p.products_id = pd.products_id) ";

		if($post_array['per_site'] == 'all') {
			$limit = '';
		} elseif(!empty($post_array['per_site'])) {
			$limit = ' LIMIT '.$post_array['per_site'];
		}

		$where_str = " WHERE
							p.products_id
						IN
							(".$products_ids.")
						AND
							p.products_status = '1'
						AND
							pd.language_id = '".(int)$_SESSION['languages_id']."'".$fsk_lock.$group_check.$limit;
		unset($_SESSION['filters']);
		foreach ($_SESSION['filter_id'] AS $id) {
			$name = xtc_db_fetch_array(xtDBquery("SELECT id, title
															FROM ".TABLE_PRODUCT_FILTER_ITEMS."
															WHERE id = '".$id."'
															AND language_id = '".$_SESSION['languages_id']."'"));
			if($namen != '') {
				$namen .= ', '.$name['title'];
			} else {
				$namen = $name['title'];
			}
			$_SESSION['filters'][] = $name;

		}
		$smarty = new Smarty;
		$smarty->caching = false;
		$smarty->assign('language', $_SESSION['language']);
		$listing_sql = $select_str.$from_str.$where_str;
		require_once(DIR_WS_MODULES.'product_filter_listing_ajax.php');
	}
	$objResponse->assign('filter_result', 'innerHTML', $output);
	$objResponse->script('jQuery("#loadingMessage").hide();jQuery("#results").show();jQuery("#filter_result").show();');
	return $objResponse;
}

#########################################################
# Filter XAJAX
#########################################################


##############################################################
# XAJAX Price
##############################################################

function getNewPrice($values) {

	$has_attr_price = false;
	$has_staffel_price = false;
	$has_special_price = false;
	$has_discount_price = false;
	$has_vpe_price = false;
	$has_weight = false;

	$objResponse = new xajaxResponse();
	$get = urldecode($values);
	$post = explode('&', $get);

	foreach($post as $posts) {
		list($key, $value) = explode('=', $posts);

		if(strstr($key, 'id['))
			$id[str_replace('id[','',str_replace(']','',$key))] = $value;

		if($key == 'products_qty')
			$qty = $value;

		if($key == 'products_update_id')
			$pid = $value;
	}
	if($qty > 0) {
		$product = new product($pid);
		$price = new xtcPrice($_SESSION['currency'], $_SESSION['customers_status']['customers_status_id']);
		
		$main_price = $price->xtcGetPrice($pid, false, $qty, $product->data['products_tax_class_id']);
		
		// Staffelpreise vorhanden?
		$check_staffel = $price->xtcGetGraduatedPrice($pid, $qty);
		// $objResponse->alert('val: '."\n".$$main_price);
		
		if($check_staffel && $_SESSION['customers_status']['customers_status_graduated_prices'] == 1) {
			$staffel = ' <span class="product_staffel_price">('.SINGLE_PRICE.' '.$price->xtcFormat($check_staffel, true, $product->data['products_tax_class_id']).')</span>';
			$has_staffel_price = true;
		}
		
	
		$special_price = $price->xtcCheckSpecial($pid);
		if ($special_price) {
			// $objResponse->alert('val: '."\n".$special_price);
			$has_special_price = true;
		}
		
		if(is_array($id)) {
			foreach($id AS $skey => $sval) {
				$attr_price = xtc_db_fetch_array(xtDBquery("SELECT
													pd.*,
													p.*
												FROM
													".TABLE_PRODUCTS_ATTRIBUTES." p
												LEFT JOIN
													".TABLE_PRODUCTS." pd ON(pd.products_id = p.products_id)
												WHERE
													p.products_id = '".$pid."'
												AND
													p.options_id = '".$skey."'
												AND
													p.options_values_id = '".$sval."'"));
				
				if($attr_price['options_values_price'] > 0) {
					$has_attr_price = true;
				}
				//Attribut VPE
				$products_price_vpe = $price->xtcGetPrice($product->data['products_id'], false, 0, $product->data['products_tax_class_id'], $product->data['products_price']);

				require_once (DIR_FS_INC . 'xtc_get_vpe_name.inc.php');
				if($attr_price['attributes_vpe_status'] == 1 && $attr_price['attributes_vpe_value'] > 0 && $attr_price['options_values_price'] != '0.0000') {
					if ($attr_price['price_prefix'] == '+') {
						$vpe_price = $price->xtcAddTax($product->data['products_price'] + $attr_price['options_values_price'] * (1 / $attr_price['attributes_vpe_value']), $price->TAX[$product->data['products_tax_class_id']]);
						$vpe_price = $price->xtcFormat($vpe_price, true).TXT_PER.xtc_get_vpe_name($attr_price['attributes_vpe']);
					} elseif ($attr_price['price_prefix'] == '=') {
						$vpe_price = $price->xtcAddTax($attr_price['options_values_price'] * (1 / $attr_price['attributes_vpe_value']), $price->TAX[$product->data['products_tax_class_id']]);
						$vpe_price = $price->xtcFormat($vpe_price, true).TXT_PER.xtc_get_vpe_name($attr_price['attributes_vpe']);
					} else {
						$vpe_price = $price->xtcAddTax($product->data['products_price'] - $attr_price['options_values_price'] * (1 / $attr_price['attributes_vpe_value']), $price->TAX[$product->data['products_tax_class_id']]);
						$vpe_price = $price->xtcFormat($vpe_price, true).TXT_PER.xtc_get_vpe_name($attr_price['attributes_vpe']);
					}
					
					$has_vpe_price = true;

				} elseif ($product->data['products_vpe_status'] == 1 && $product->data['products_vpe_value'] > 0 && $products_price_vpe > 0 && $attr_price['options_values_price'] == '0.0000') {
					$vpe_price = $price->xtcFormat($products_price_vpe * (1 / $product->data['products_vpe_value']), true) . TXT_PER . xtc_get_vpe_name($product->data['products_vpe']);
					$has_vpe_price = true;
				}
				//Attribut VPE END
				
				//Product Weight
				if ($attr_price['options_values_weight'] != '0.0000' && $attr_price['weight_prefix'] == '+') {
					$prod_weight = $product->data['products_weight'] + $attr_price['options_values_weight'];
					$prod_weight = number_format($prod_weight, 3, '.', '');
					$has_weight = true;
				} elseif ($attr_price['options_values_weight'] != '0.0000' && $attr_price['weight_prefix'] == '-') {
					$prod_weight = $product->data['products_weight'] - $attr_price['options_values_weight'];
					$prod_weight = number_format($prod_weight, 3, '.', '');
					$has_weight = true;
				} elseif ($attr_price['options_values_weight'] == '0.0000' && $product->data['products_weight'] > 0){
					$prod_weight = $product->data['products_weight'];
					$has_weight = true;
				}
				//Product Weight END

				$val_price = $price->xtcFormat($attr_price['options_values_price'], false, $attr_price['products_tax_class_id']);

				if($price->cStatus['customers_status_discount_attributes'] == 1 && $price->cStatus['customers_status_discount'] != 0.00) {
					$discount = $price->cStatus['customers_status_discount'];
					if($attr_price['products_discount_allowed'] < $price->cStatus['customers_status_discount']) {
						$discount = $attr_price['products_discount_allowed'];
					}

					$has_discount_price = true;

				} elseif ($price->cStatus['customers_status_discount_attributes'] != 1 && $price->cStatus['customers_status_discount'] != 0.00) {
					$discount = $price->cStatus['customers_status_discount'];
					if($attr_price['products_discount_allowed'] < $price->cStatus['customers_status_discount']) {
						$discount = $attr_price['products_discount_allowed'];
					}
					$has_discount_price = true;
				} else {
					$has_discount_price = false;
				}

				if ($attr_price['price_prefix'] == '+') {
					$main_price += ($val_price - $val_price / 100 * $discount);
					$attribute_price += $val_price;
				} elseif ($attr_price['price_prefix'] == '=') {
					$main_price = ($val_price - $val_price / 100 * $discount);
					$attribute_price = $val_price;
				} else {
					$main_price -= ($val_price - $val_price / 100 * $discount);
					$attribute_price -= $val_price;
				}
			}
		}	
		
		$old_price = '<div class="product_ajax_price">('.trim($price->xtcGetPrice($pid, true, 1, $product->data['products_tax_class_id'])).')</div>';
		
		// $objResponse->alert('val: '."\n".$main_price);
		if ($main_price <> ($main_price+$attribute_price)) {
			//Preis mit Attributen und Aufpreis
			$main_price = $price->xtcFormat($main_price*$qty, true).$old_price;
		} elseif (!is_array($id) && !$has_attr_price && !$has_staffel_price && !$has_special_price && $qty > 1) {
			//Preis alleine
			$main_price = $price->xtcFormat($main_price*$qty, true).'<div class="product_ajax_price">('.FROM.trim($price->xtcGetPrice($pid, true, 1, $product->data['products_tax_class_id'])).')</div>';
		} elseif ($has_attr_price) {
			// Attribute vorhanden
			$main_price = $price->xtcFormat($main_price*$qty, true).$old_price;
		} elseif ($has_staffel_price) {
			// Staffelpreise vorhanden
			$min_price = xtc_db_fetch_array(xtDBquery("SELECT MIN(personal_offer) as min_price FROM ".TABLE_PERSONAL_OFFERS_BY.$price->actualGroup." WHERE products_id = '".$pid."' "));
			$possible_qty = xtc_db_fetch_array(xtDBquery("SELECT MAX(quantity) AS qty FROM ".TABLE_PERSONAL_OFFERS_BY.$price->actualGroup." WHERE products_id = '".$pid."' AND quantity <= '".$qty."'"));
			$max_qty = xtc_db_fetch_array(xtDBquery("SELECT MAX(quantity) AS qty FROM ".TABLE_PERSONAL_OFFERS_BY.$price->actualGroup." WHERE products_id = '".$pid."'"));
			$staffel_preis = xtc_db_fetch_array(xtDBquery("SELECT personal_offer FROM ".TABLE_PERSONAL_OFFERS_BY.$price->actualGroup." WHERE products_id = '".$pid."' AND quantity = '".$possible_qty['qty']."'"));
														
			if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 0) {
				$final_price = $check_staffel*$qty;
				$main_price = $price->xtcFormat($final_price, true).'<div class="product_ajax_price">('.SINGLE_PRICE.($qty<$max_qty['qty']?'bei '.$qty:FROM.$max_qty['qty']).' Stk. = '.$price->xtcFormat($staffel_preis['personal_offer'], true).')</div>';
			} else {
				$final_price = $price->xtcAddTax($check_staffel*$qty, $price->TAX[$product->data['products_tax_class_id']]);
				$main_price = $price->xtcFormat($final_price, true).'<div class="product_ajax_price">('.SINGLE_PRICE.($qty<$max_qty['qty']?'bei '.$qty:FROM.$max_qty['qty']).' Stk. = '.$price->xtcFormat($price->xtcAddTax($staffel_preis['personal_offer'], $price->TAX[$product->data['products_tax_class_id']]), true).')</div>';				
			}
			
		} elseif ($has_special_price) {
			//Sonderpreis
			if ($_SESSION['customers_status']['customers_status_show_price_tax'] == '1') {
				$main_price = $price->xtcFormatSpecial($pID, $price->xtcAddTax(($special_price*$qty), $price->TAX[$product->data['products_tax_class_id']]), $price->xtcAddTax($price->getPprice($pid), $price->TAX[$product->data['products_tax_class_id']]), true, 0, $qty);
			} else {
				$main_price = $price->xtcFormatSpecial($pID, $price->xtcAddTax(($special_price*$qty), 0), $price->xtcAddTax($price->getPprice($pid), 0), true, 0, $qty);
			}
		} elseif ($qty > 1) {
			//Normalpreis Menge >1
			$main_price = $price->xtcFormat($main_price*$qty, true).' <div class="product_ajax_price">('.SINGLE_PRICE.trim($price->xtcGetPrice($pid, true, 1, $product->data['products_tax_class_id'])).')</div>';
		} elseif ($has_discount_price) {
			// Produkt Rabatt
			$main_price = '<div class="product_ajax_price">'.trim($price->xtcGetPrice($pid, true, 1, $product->data['products_tax_class_id'])).'</div>';
			
		} else {
			$main_price = '<div itemprop="offers" itemscope itemtype="http://schema.org/Offer"><span itemprop="price">'.$price->xtcFormat($main_price, true).'</span></div>';
		}

		if($has_vpe_price) {
			$objResponse->assign('produtc_vpe', 'innerHTML', $vpe_price);
		}
		if($has_weight) {
			$objResponse->assign('prod_weight', 'innerHTML', $prod_weight);
		}
		$objResponse->assign('product_info_price', 'innerHTML', $main_price);
	}
	return $objResponse;
}


##############################################################
# XAJAX Price
##############################################################

if (file_exists(DIR_WS_INCLUDES . 'addons/xajax_addon.php')) {
	include (DIR_WS_INCLUDES . 'addons/xajax_addon.php');
}

$xajax->processRequests();
$xajax->printJavascript();